package com.gzsxy.sso.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.gzsxy.sso.common.dto.request.RoleRequest;
import com.gzsxy.sso.common.dto.response.MenuRsp;
import com.gzsxy.sso.common.dto.response.RoleFunctionRsp;
import com.gzsxy.sso.common.exception.impl.BusinessException;
import com.gzsxy.sso.common.exception.impl.CustomAssert;
import com.gzsxy.sso.common.result.ResultCodeEnum;
import com.gzsxy.sso.common.utils.StringUtils;
import com.gzsxy.sso.core.dao.UserRoleMapper;
import com.gzsxy.sso.core.entity.Role;
import com.gzsxy.sso.core.dao.RoleMapper;
import com.gzsxy.sso.core.entity.vo.RoleQueryVo;
import com.gzsxy.sso.core.model.SessionUser;
import com.gzsxy.sso.core.service.RoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gzsxy.sso.core.utils.SessionUserUtil;
import com.gzsxy.sso.core.utils.TreeUtil;
import com.gzsxy.sso.core.utils.ValidateUtil;
import org.apache.commons.lang3.BooleanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zxl
 * @since 2021-11-10
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {


    Logger log = LoggerFactory.getLogger(RoleServiceImpl.class);

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;




    /**
     * @description: 查询所有的角色
     * @param
     * @return
     */
    @Override
    public List<Role> getAllRoles() {
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        List<Role> role = baseMapper.selectList(queryWrapper);
        return role;
    }




    /**
     * @description: 查询角色下所有功能列表
     * @param
     * @return
     */
    @Override
    public List<RoleFunctionRsp> findFunctionByRoles() {
        //2.查询每个角色对应的所有权限
        List<RoleFunctionRsp> rolefunlist = roleMapper.findFunctionByRoles();

        rolefunlist.forEach(roleFunctionRsp -> {
            //查询当前角色下的所有功能
            List<MenuRsp> menu = roleFunctionRsp.getChildren();
            //转换为树结构（根据父id去查询进行处理）
            List<MenuRsp> build = TreeUtil.build(menu, Comparator.comparing(MenuRsp::getOrderId).reversed());
            roleFunctionRsp.setChildren(build);
        });
        return rolefunlist;
    }

    /**
     * @description: 添加角色
     * @param
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addRole(RoleRequest roleRequest) {
        LambdaQueryWrapper<Role> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(Role::getRoleName,roleRequest.getRoleName());
        Role role = roleMapper.selectOne(wrapper);
        // 角色名唯一校验
        CustomAssert.notTrue(ObjectUtils.isEmpty(role), ResultCodeEnum.ROLE_NAME_EXIST.getMessage(),ResultCodeEnum.ROLE_NAME_EXIST.getCode());

        if (BooleanUtils.isTrue(roleRequest.getIsAdmin()) && !SessionUserUtil.isAdmin()){
            //非管理员不能创建管理员角色
            throw new BusinessException(ResultCodeEnum.REQUIRE_ADMIN_PERMISSION.getMessage());
        }
        String pingYin = StringUtils.getPingYin(roleRequest.getRoleName());
        String pinYinHeadChar = StringUtils.getPinYinHeadChar(roleRequest.getRoleName());
        //角色代码唯一校验
//        ValidateUtil.assertUnique(baseMapper::existByCode,);
        Role role1 = new Role();
        BeanUtils.copyProperties(roleRequest,role1);
        role1.setCode(pinYinHeadChar);
        role1.setScode(pingYin);
//        //获取当前登录用户
//        SessionUser sessionUser = SessionUserUtil.getSessionUser();
//        role1.setAddUser(sessionUser.getUserName());
//        role1.setUpdateUser(sessionUser.getUserName());
        roleMapper.insert(role1);
    }



    /**
     * @description: 角色分页查询
     * @param
     * @return
     */
    @Override
    public IPage<RoleFunctionRsp> selectPage(IPage<?> pageParam, RoleQueryVo roleQueryVo) {
        //显示分页查询列表
        // 1.排序：按照sort字段排序
        QueryWrapper<RoleFunctionRsp> queryWrapper = new QueryWrapper<>();//条件构造器
        queryWrapper.orderByDesc("order_id");//通过sort字段进行升序
        queryWrapper.eq("is_deleted",0);


        if (ObjectUtils.isEmpty(roleQueryVo)){
            IPage<RoleFunctionRsp> rspIPage = baseMapper.selectPageByRoleQueryVo(pageParam,queryWrapper);
            List<RoleFunctionRsp> records = rspIPage.getRecords();
            records.forEach(roleFunctionRsp -> {
                //查询当前角色下的所有功能
                List<MenuRsp> menu = roleFunctionRsp.getChildren();
                //转换为树结构（根据父id去查询进行处理）
                List<MenuRsp> build = TreeUtil.build(menu, Comparator.comparing(MenuRsp::getOrderId).reversed());
                roleFunctionRsp.setChildren(build);
            });
            rspIPage.setRecords(records);
            return rspIPage;
        }

        String roleName = roleQueryVo.getRoleName();
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(roleName)){
            queryWrapper.like("role_name",roleName);
        }
        IPage<RoleFunctionRsp> rspIPage = baseMapper.selectPageByRoleQueryVo(pageParam,queryWrapper);
        List<RoleFunctionRsp> records = rspIPage.getRecords();
        records.forEach(roleFunctionRsp -> {
            //查询当前角色下的所有功能
            List<MenuRsp> menu = roleFunctionRsp.getChildren();
            //转换为树结构（根据父id去查询进行处理）
            List<MenuRsp> build = TreeUtil.build(menu, Comparator.comparing(MenuRsp::getOrderId).reversed());
            roleFunctionRsp.setChildren(build);
        });
        rspIPage.setRecords(records);
        return rspIPage;
    }


    /**
     * @description: 修改角色
     * @param
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateRole(RoleRequest roleRequest) {
        Role role = baseMapper.selectById(roleRequest.getId());
        //禁止编辑超级管理员
        if (role.getIsSadmin()){
            throw new BusinessException(ResultCodeEnum.ROLE_SADMIN_UPDATE_NOT_ALLOW.getMessage());
        }
        //非管理员不能编辑管理员角色
        if (roleRequest.getIsAdmin() && !SessionUserUtil.isAdmin()){
            throw new BusinessException(ResultCodeEnum.REQUIRE_ADMIN_PERMISSION.getMessage());
        }
        //角色不存在，抛出异常
        CustomAssert.notTrue(ObjectUtils.isNotEmpty(role),ResultCodeEnum.ROLE_NOT_FOUND.getMessage(),ResultCodeEnum.ROLE_NOT_FOUND.getCode());
        LambdaQueryWrapper<Role> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(Role::getRoleName,roleRequest.getRoleName());
        Role role1 = roleMapper.selectOne(wrapper);
        //若更改了角色名，才去判角色名唯一
        if (!role.getRoleName().equals(roleRequest.getRoleName())){
            // 角色名唯一校验
            CustomAssert.notTrue(ObjectUtils.isEmpty(role1), ResultCodeEnum.ROLE_NAME_EXIST.getMessage(),ResultCodeEnum.ROLE_NAME_EXIST.getCode());
        }
        Role role2 = new Role();
        BeanUtils.copyProperties(roleRequest,role2);
        //角色编码设置
        String pingYin = StringUtils.getPingYin(roleRequest.getRoleName());
        String pinYinHeadChar = StringUtils.getPinYinHeadChar(roleRequest.getRoleName());
        role2.setCode(pinYinHeadChar);
        role2.setScode(pingYin);
//        //获取当前登录用户
//        SessionUser sessionUser = SessionUserUtil.getSessionUser();
//        role2.setUpdateUser(sessionUser.getUserName());
        baseMapper.updateById(role2);
    }


    /**
     * @description: 删除角色
     * @param
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteRole(String id) {
        Role role = baseMapper.selectById(id);
        //角色不存在，抛出异常
        CustomAssert.notTrue(ObjectUtils.isNotEmpty(role),ResultCodeEnum.ROLE_NOT_FOUND.getMessage(),ResultCodeEnum.ROLE_NOT_FOUND.getCode());
        //禁止删除超级用户
        if (role.getIsSadmin()){
            throw new BusinessException(ResultCodeEnum.ROLE_SADMIN_DELETE_NOT_ALLOW.getMessage());
        }
        //检查是否存在关联用户
        ValidateUtil.isFalse(userRoleMapper.existByRoleId(id),ResultCodeEnum.ROLE_DELETE_FAILED_EXIST_USER.getMessage());
//        //获取当前登录用户
//        SessionUser sessionUser = SessionUserUtil.getSessionUser();
//        role.setUpdateUser(sessionUser.getUserName());
        baseMapper.updateById(role);
        baseMapper.deleteById(id);
    }

    /**
     * @description: 通过id查询角色
     * @param
     * @return
     */
    @Override
    public Role selectById(String roleId) {
        return baseMapper.selectById(roleId);
    }





}
